package com.wwcom.darteagle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.fragment.StatsDetailsFragment;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.Leg;
import com.wwcom.darteagle.model.Match;
import com.wwcom.darteagle.model.Player;
import com.wwcom.darteagle.model.Set;
import com.wwcom.darteagle.util.Messages;
import com.wwcom.darteagle.view.ScrollAwareViewPager;

public class MatchStatsActivity extends FragmentActivity {
	private long matchId;
	private long playerId;
	LocalBroadcastManager mLocalBroadcastManager;
	private boolean isMatchStats;
	private Match match;	
	public int numFragments;
	private static final String RELOAD_MATCH= "reloadMatch";
	
    MyAdapter mAdapter;

    ScrollAwareViewPager mPager;
	
	
	/** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		 
        numFragments= 1;
        
        //if matchId is -1 then we are displaying the current match, otherwise a specific
        // database id is passed
        matchId= -1;
        playerId= -1;
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
        	matchId= extras.getLong(StatsDetailsFragment.MATCH_ID);
        	playerId= extras.getLong(StatsDetailsFragment.PLAYER_ID);
        }
        Log.d("MatchStatsActivity","MatchId: "+matchId);
        //recover saved state
        GlobalAppData gd= GlobalAppData.getSingletonInstance();
        if (savedInstanceState != null) {
			if (savedInstanceState.getBoolean(RELOAD_MATCH) && gd.match == null) {				
				DartEagleDatabase db= new DartEagleDatabase(this);             	    	
				gd.match= db.getResumableMatch();
				db.close();
			}
			matchId= savedInstanceState.getLong(StatsDetailsFragment.MATCH_ID);
			playerId= savedInstanceState.getLong(StatsDetailsFragment.PLAYER_ID);
		}
        //load match
        if (matchId >= -1) {
        	match= gd.getMatch(matchId, this);
    	} else {
			DartEagleDatabase db= new DartEagleDatabase(this);  
			Player player= db.getPlayer(playerId);
			match= db.getPlayerOverallMatch(player);
			db.close();
    	}
        
        numFragments= getNumStatsFragments();
        Log.d("MatchStatsActivity","numFragments: "+numFragments);
        setContentView(R.layout.matchstats);
        
        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ScrollAwareViewPager)findViewById(R.id.fragment_pager);
        mPager.setAdapter(mAdapter);
	    //don't scroll the viewpager when we swipe the scroll view if it is active
	    //int nPlayers= match.getMatchPlayers().size(); 
	    //if (nPlayers > StatsDetailsFragment.MAX_PLAYERS_ON_SCREEN)        
	    	mPager.setChildId(R.id.match_stats_horizontal_scroll);
	    
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        
    }
    
    @Override
    public void onBackPressed() {
    	if (!isMatchStats)
    		broadcastShowTips();
    	super.onBackPressed();
        return;
    }  
    
    @Override 
    protected void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState(outState);
    	//note that we have been killed and will need to reload the gd.match from
    	// the database
    	outState.putBoolean(RELOAD_MATCH, true);
    	outState.putLong(StatsDetailsFragment.MATCH_ID,matchId);
    	outState.putLong(StatsDetailsFragment.PLAYER_ID,playerId);
    }    
    
    
    private void broadcastShowTips() {
			Intent intent=new Intent();
			intent.setAction(Messages.SHOWTIPS_MATCHSTATS);		
			mLocalBroadcastManager.sendBroadcast(intent);
	}
    
    //manage movement between stats views in a match 
    private int getNumStatsFragments() {
    	int numberStatsFragments= 1; //the match stats 
    	
    	if (matchId == -2) {
        	return numberStatsFragments;
    	}
    	
    	if (match.getNumSets() > 0) { //we must be in a sets match
    		for (Set s : match.getSets()) {
        		numberStatsFragments++; //the sets stats
        		numberStatsFragments+= s.getLegs().size();
    		}

    	} else { //we are in a legs only match
    		numberStatsFragments+= match.getLegs().size();
    	}
    	
    	return numberStatsFragments;
    }

    
    private Fragment getStatsFragment(int fragmentId) {
    	Log.d("MatchStatsActivity","Requesting fragment: "+fragmentId);
    	if (fragmentId == 0) {
        	Log.d("MatchStatsActivity","Got match stats");
        	return getFragment(-1,-1,fragmentId);
    	} else if (match.getNumSets() > 0) { //we must be in a sets match
    		int setInd= -1;
    		int fragmentCounter= fragmentId;
    		for (Set s : match.getSets()) {
    			setInd++;
        		int legInd= -1;
    			fragmentCounter--;
    			if (fragmentCounter == 0) {
    	        	return getFragment(legInd,setInd,fragmentId);
    			}
    			for (@SuppressWarnings("unused") Leg l : s.getLegs()) {
    				legInd++;
        			fragmentCounter--;
        			if (fragmentCounter == 0) {
        	        	return getFragment(legInd,setInd,fragmentId);
        			}    				
    			}
    		}

    	} else { //we are in a legs only match
    		int fragmentCounter= fragmentId;
    		int legInd= -1;
			for (Leg l : match.getLegs()) {
	        	Log.d("MatchStatsActivity","Viewing leg "+l);
				legInd++;
    			fragmentCounter--;
    			if (fragmentCounter == 0) {
    	        	Log.d("MatchStatsActivity","Got leg stats "+legInd);
    	        	return getFragment(legInd,-1,fragmentId);
    			}    				
			}
    	}
    	
    	Log.d("MatchStatsActivity","Returning null fragment!");
    	return null;
    }
    
    private StatsDetailsFragment getFragment(int legInd, int setInd, int fragmentId) {
    	StatsDetailsFragment newFragment = new StatsDetailsFragment();
    	Bundle args = new Bundle();
    	args.putLong(StatsDetailsFragment.MATCH_ID, matchId);
    	args.putLong(StatsDetailsFragment.PLAYER_ID, playerId);
    	args.putInt(StatsDetailsFragment.LEG_IND, legInd);
    	args.putInt(StatsDetailsFragment.SET_IND, setInd);
    	args.putInt(StatsDetailsFragment.NUM_IN_LIST, numFragments);
    	args.putInt(StatsDetailsFragment.POS_IN_LIST, fragmentId);        	
    	newFragment.setArguments(args);    		    				
    	return newFragment;    	
    }
    

    
    //viewpager adapter
    public class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return numFragments;
        }

        @Override
        public Fragment getItem(int position) {
            return getStatsFragment(position);
        }
    }    
    
    
	
}